<template>
	<div class="w-full">
		<el-button type="primary" class="mb-[20px]" icon="el-icon-plus" @click="handleSave">添加自提地址</el-button>
		<div class="md:w-[800px]">
			<el-table ref="selfMention" v-loading="loading" :data="selfMentionList">
				<el-table-column :formatter="emptyToString" align="center" width="180" label="店铺名称" prop="storeName" />
				<el-table-column :formatter="emptyToString" align="center" width="180" label="店铺电话" prop="phone" />
				<el-table-column :formatter="emptyToString" align="center" width="180" label="可自提时间" prop="selfMentionTime" />
				<el-table-column :formatter="emptyToString" align="center" width="180" label="所在地区">
					<template slot-scope="scope"> {{ scope.row.provinceName }}{{ scope.row.cityName }}{{ scope.row.countyName }} </template>
				</el-table-column>
				<el-table-column :formatter="emptyToString" align="center" min-width="180" label="详细地址" prop="addressDetail" />
				<el-table-column :formatter="emptyToString" align="center" label="操作" width="200" fixed="right" header-align="center">
					<template slot-scope="scope">
						<el-button v-hasPermi="['mall:goods:edit']" type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
						<el-button v-hasPermi="['mall:goods:remove']" type="danger" @click="handleDelete(scope.row)">删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!--新增或编辑自提地点-->
		<l-dialog v-model="openDetails" :title="title" width="1000px" @close="handleClose">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="店铺名称：" prop="storeName">
					<el-input v-model.trim="form.storeName" placeholder="请输入店铺名称" />
				</el-form-item>
				<el-form-item label="店铺电话：" prop="phone">
					<el-input v-model.trim="form.phone" placeholder="请输入店铺电话" />
				</el-form-item>
				<el-form-item label="自提时间：" prop="selfMentionTime">
					<el-time-picker
						v-model.trim="form.selfMentionTime"
						is-range
						class="!w-[299px]"
						format="HH:mm:ss"
						value-format="HH:mm:ss"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						placeholder="选择时间范围"
					>
					</el-time-picker>
				</el-form-item>
				<el-form-item label="所在地区：" prop="location">
					<el-cascader ref="cascaderAddr" v-model.trim="form.location" size="medium" value="label" :options="option" placeholder="请选择所在地区" @change="cityChange"></el-cascader>
				</el-form-item>
				<el-form-item label="详细地址：" prop="address">
					<el-input v-model.trim="form.addressDetail" readonly placeholder="请输入详细地址" />
				</el-form-item>
				<div class="map-box">
					<!--					<div class="input">-->
					<!--						<el-input v-model.trim="keyword" placeholder="请输入内容" @input="change"></el-input>-->
					<!--						<el-button style="margin-left: 10px" type="primary" icon="el-icon-search" @click="add">搜索</el-button>-->
					<!--					</div>-->
					<div id="option-box" ref="option-box" class="option" v-html="htmlStr">
						<div id="option" ref="option"></div>
					</div>
					<baidu-map v-if="showMap" class="bm-view" ak="R3FLmsY6rMbuwL12ilZuCjzmoZiFC5fY" :center="thsAreaCode" :zoom="11">
						<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
						<bm-control :offset="{ width: '10px', height: '10px' }">
							<bm-auto-complete v-model="searchKeyword" :sug-style="{ zIndex: 1 }" @searchcomplete="searchcomplete">
								<el-autocomplete v-model="searchKeyword" :debounce="500" class="search !w-[200px] ml-[10px] mt-[10px]" :fetch-suggestions="querySearchAsync" placeholder="请输入关键词">
									<template slot-scope="{ item }">
										<div class="flex w-full justify-between items-center">
											<span>{{ item.address }}</span>
											<span class="text-[#c0c0c0]">{{ item.tips }}</span>
										</div>
									</template>
								</el-autocomplete>
							</bm-auto-complete>
						</bm-control>
						<bm-local-search :keyword="searchKeyword" :auto-viewport="true" @infohtmlset="infohtmlset"></bm-local-search>
					</baidu-map>
				</div>
			</el-form>

			<div slot="footer" class="mt-[20px]">
				<el-button type="primary" @click="submitForm">保 存</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</l-dialog>
	</div>
</template>
<script>
import { listSelfmention, getSelfmention, delSelfmention, addSelfmention, updateSelfmention } from '@/api/mall/selfmention';
import { options } from '@/api/mall/detailedAddress';
import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
import { BmLocalSearch, BmNavigation, BmMarker, BmControl, BmAutoComplete, BmView } from 'vue-baidu-map';
export default {
	name: 'SelfMention',
	components: {
		BaiduMap,
		BmLocalSearch,
		BmNavigation,
		BmMarker,
		BmControl,
		BmAutoComplete,
		BmView,
	},

	data() {
		return {
			// 遮罩层
			loading: true,
			loading1: false,
			selfMentionList: [],
			title: '',
			map: null,
			openDetails: false,
			// 自提表单参数
			form: {},
			list: '',
			rules: {
				storeName: [{ required: true, message: '店铺名称为空', trigger: 'blur' }],
				phone: [{ required: true, message: '店铺电话为空', trigger: 'blur' }],
				selfMentionTime: [{ required: true, message: '自提时间为空', trigger: 'blur' }],
				location: [{ required: true, message: '所在地区不能为空', trigger: 'blur' }],
				addressDetail: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
			},
			//地区
			option: options,
			location: '',
			// 搜索参数
			keyword: '',
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				type: null,
				title: null,
				content: null,
				tenantId: null,
			},
			htmlStr: '',
			searchKeyword: '',
			thsAreaCode: '北京',
			showMap: true,
			lng: '',
			lat: '',
			timeout: null,
			restaurants: [],
		};
	},
	created() {
		this.getselfmentionList();
	},
	methods: {
		cityChange() {
			this.showMap = false;
			this.thsAreaCode = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels[1];
			this.$nextTick(() => {
				this.showMap = true;
			});
		},
		add() {
			var f = this.$refs['option-box'];
			var childs = f.childNodes;
			for (var i = 0; i < childs.length; i++) {
				f.removeChild(childs[i]);
			}
			this.searchKeyword = this.keyword;
		},
		change() {},
		infohtmlset(value) {
			this.$set(this.form, 'addressDetail', value.address);
			this.$set(this.form, 'lat', value.point.lat);
			this.$set(this.form, 'lng', value.point.lng);
			this.searchKeyword = value.address;
		},
		resultshtmlset(value) {
			this.$refs['option-box'].appendChild(value);
		},
		initMap() {},
		/** 搜索自提地址列表 */
		getselfmentionList() {
			this.loading = true;
			listSelfmention(this.queryParams).then((response) => {
				this.selfMentionList = response.data.records;
				this.total = response.data.total;
				this.loading = false;
			});
		},
		cancel() {
			this.openDetails = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				storeName: null,
				phone: null,
				selfMentionTime: null,
				location: null,
				address: null,
				userId: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				tenantId: null,
			};
			this.resetForm('form');
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					let values = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels;
					let ids = this.$refs['cascaderAddr'].getCheckedNodes()[0].path;
					this.form.province = ids[0];
					this.form.provinceName = values[0];
					this.form.city = ids[1];
					this.form.cityName = values[1];
					this.form.county = ids[2];
					this.form.countyName = values[2];
					this.form.location = '';
					this.form.selfMentionTime = this.form.selfMentionTime.join('-');
					if (!this.form.addressDetail) {
						this.$message.error('请选择详细地址!');
					}
					if (this.form.id != null) {
						updateSelfmention(this.form).then((response) => {
							this.msgSuccess('编辑成功');
							this.openDetails = false;
							this.getselfmentionList();
						});
					} else {
						addSelfmention(this.form).then((response) => {
							this.msgSuccess('新增成功');
							this.openDetails = false;
							this.getselfmentionList();
						});
					}
				}
			});
		},
		handleClose() {
			this.openDetails = false;
			this.restaurants = [];
			this.searchKeyword = '';
			this.thsAreaCode = '北京';
		},
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			getSelfmention(id).then((response) => {
				this.form = response.data;
				console.log(response.data);
				this.thsAreaCode = response.data.cityName;
				this.form.selfMentionTime = this.form.selfMentionTime.split('-');
				this.form.location = [this.form.province, this.form.city, this.form.county];

				this.openDetails = true;
				this.title = '编辑自提地址';
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let ids = [row.id || this.ids];
			this.$confirm('是否确认删除自提地址编号为"' + ids + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delSelfmention(ids);
				})
				.then(() => {
					this.getselfmentionList();
					this.msgSuccess('删除成功');
				});
		},
		handleSave() {
			this.title = '添加自提地址';
			this.openDetails = true;
		},
		createStateFilter(queryString) {
			return (state) => {
				return state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
			};
		},
		querySearchAsync(queryString, cb) {
			const results = this.restaurants;

			console.log(results, 'results');
			clearTimeout(this.timeout);
			this.timeout = setInterval(() => {
				if (results.length > 0 && this.searchKeyword) {
					cb(results);
				} else if (!this.searchKeyword) {
					cb([]);
				}
			}, 500);
		},
		searchcomplete(val) {
			if (!this.searchKeyword) {
				this.restaurants = [];
				return;
			}
			this.restaurants = val.Yr.map((item) => ({
				value: item.business,
				tips: item.city + item.district,
				address: item.business,
			}));
		},
	},
};
</script>

<style scoped lang="scss">
.search {
	::v-deep {
		.el-input {
			width: 200px;
			max-width: 200px;
		}
	}
}
.map-box {
	position: relative;
	.option {
		position: absolute;
		z-index: 99;
		top: 56px;
		left: 20px;
		width: 200px;
	}
	.input {
		position: absolute;
		z-index: 99;
		top: 20px;
		left: 20px;
		width: 300px;
		display: flex;
	}
}
.bm-view {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 800px;
}
</style>
